package com.wx.controller;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wx.common.utils.ImagePathUtil;
import com.wx.pojo.Source;
import com.wx.pojo.SourceDetail;
import com.wx.service.PublishService;
import com.wx.service.SourceDetailService;
import com.wx.utils.FastDFSClient;
/**
 * 服务信息发布
 *
 */
@Controller
@RequestMapping("/publish")
public class PublishController {

	@Autowired
	private PublishService publishService;
	
	@Autowired
	private SourceDetailService sourceDetailService;
	/**
	 * 发布提供服务
	 * demend_or_idle  0：代表发布提供服务信息  1：代表发布需求信息 
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/publishSource",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object>insertPublish(@RequestParam("sort_id") String sortid,
			@RequestParam("category_id")String categoryid,@RequestParam("major")String source_name,
			@RequestParam("telephone")String source_phone,@RequestParam("score")String sourcecount,
			@RequestParam("salary")String sourceprice,@RequestParam("money")String sourcedeposit,
			@RequestParam("remark")String source_text,@RequestParam("province")String province,
			@RequestParam("city")String city,@RequestParam("county")String county,
			@RequestParam("addressName")String source_address,@RequestParam("img_arr")String img_arr,
			@RequestParam("user_id")String user_id) {
		
		
		Map<String,Object> modelMap=new HashMap<String,Object>();
		Source source = new Source();
		
		
		
		if(sortid!=null && sortid!=""&& categoryid!=null  && categoryid!=""&& source_name!=null && source_name!=""
		   && source_phone!=null && source_phone!="" && sourcecount!=null && sourcecount!="" && sourceprice!=null && sourceprice!=""
		   && sourcedeposit!=null  && sourcedeposit!=null && source_address!=null && source_address!="" && img_arr!=null &&img_arr!="" ) {
			
			Integer sort_id=Integer.parseInt(sortid);//获取服务类别
			Integer category_id=Integer.parseInt(categoryid);//获取服务类别
//			String source_name=request.getParameter("major");//获取服务名称
			
//			String source_phone=request.getParameter("telephone");
			Integer source_count=Integer.parseInt(sourcecount);//获取数量
			Double source_price =Double.parseDouble(sourceprice);//获取佣金
			
			Double source_deposit=Double.parseDouble(sourcedeposit);//获取押金
//			String source_text=request.getParameter("remark");//获取描述
//			String province=request.getParameter("province");//获取省份
			
//			String city=request.getParameter("city");//获取城市
//			String county=request.getParameter("county");//获取县城曲线
//			String source_address=request.getParameter("addressName");//获取地址
			
			String[] imagePaths=ImagePathUtil.sourceImagePath(img_arr);
//			String user_id=request.getParameter("user_id");
			
			System.out.println("sort_id: "+sort_id);
			System.out.println("category_id: "+category_id);
			System.out.println("source_name: "+source_name);
			
			System.out.println("source_phone: "+source_phone);
			System.out.println("source_count: "+source_count);
			System.out.println("source_price: "+source_price);
				
			System.out.println("source_deposit: "+source_deposit);
			System.out.println("source_text: "+source_text);
			System.out.println("province: "+province);
			
			System.out.println("city: "+city);
			System.out.println("county: "+county);
			System.out.println("source_address: "+source_address);
			
			System.out.println("imagePaths: "+imagePaths);
			
			System.out.println("user_id:"+user_id);
			
			source.setSort_id(sort_id);
			source.setCategory_id(category_id);
			source.setSource_name(source_name);
			
			source.setSource_phone(source_phone);
			source.setSource_count(source_count);
			source.setSource_price(source_price);
			

			source.setSource_deposit(source_deposit);
			source.setSource_text(source_text);
			source.setProvince(province);
			
			source.setCity(city);
			source.setCounty(county);
			source.setSource_address(source_address);
			
			String source_image="";
			for (String path : imagePaths) {
				
				source_image+=path+",";
			}
			System.out.println(source_image);
			if(source_image!=""&&source_image!=null) {
				source_image=source_image.substring(0, source_image.length()-1);
				source.setSource_image(source_image);
			}
			source.setUser_id(user_id);
			source.setDemend_or_idle(0);//0 选择发布提供的服务信息 ；1 选择发布需求信息
			
			System.out.println(source);
			
			publishService.insertSource(source);
			
			if(source.getSort_id()!=0) {
				modelMap.put("success", "success");
			}else {
				modelMap.put("false", "false");
			}
			
			modelMap.put("success", "success");
			return modelMap;
		}else {
			modelMap.put("success", "fail");
			return modelMap;
		}
		
	}
	
	
	
	/**
	 * 0代表上传图片服务器成功，1代表失败
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/wx_upload")
	@ResponseBody
	public Map<String,Object> wx_upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		Map<String,Object> modelMap=new HashMap<String,Object>();
		
		DiskFileItemFactory factory = new DiskFileItemFactory();
	    ServletFileUpload upload = new ServletFileUpload(factory);
	    String fileId = null;
//	    String json = "{\"success\":false,\"fileName\":\"" + fileId + "\"}";
	    String pathUrl=ResourceBundle.getBundle("properties/FastDFSConfPath").getString("image_server");
	    System.out.println(pathUrl);
	    InputStream inStream = null;
	    String imageExtension=null;
	    try {
	        //可以上传多个文件
	        List<FileItem> list = (List<FileItem>)upload.parseRequest(request);
	        for(FileItem item : list){
	            //获取表单的属性名字
	            String name = item.getFieldName();
	            //如果获取的 表单信息是普通的 文本 信息
	            if(item.isFormField()){
	                //获取用户具体输入的字符串 ，名字起得挺好，因为表单提交过来的是 字符串类型的
	                String value = item.getString() ;
	                request.setAttribute(name, value);
	            }else {
	                //获取路径名
	            	if(item.getName()!=null || item.getName()!="") {
	            		String filename = item.getName();
		                int lastIndex=filename.lastIndexOf(".");
		                imageExtension =filename.substring(lastIndex+1);
		                System.out.println(imageExtension);	
		                System.out.println(filename);
		                request.setAttribute(name, filename);
		                inStream = item.getInputStream() ;
	            	}else {
	            		modelMap.put("errno", 2);//没有上传图片
	            		return modelMap;
	            	}
	                
	            }
	        }
	        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
	        byte[] buff = new byte[1024*1024*100];
	        int rc = 0;
	        while ((rc = inStream.read(buff, 0, 1024*1024*100)) > 0) {
	            swapStream.write(buff, 0, rc);
	        }
	        byte[] bytes = swapStream.toByteArray();
	        String confPath= ResourceBundle.getBundle("properties/FastDFSConfPath").getString("path");
	        FastDFSClient fastDFSClient = new FastDFSClient(confPath);
	        fileId = fastDFSClient.uploadFile(bytes,imageExtension);
	        System.out.println(fileId);
	        if (fileId != null && imageExtension!=null) {
//	            json = "{\"success\":true,\"pathUrl\":\"" + pathUrl + "\",\"fileName\":\"" + fileId + "\"}";
	        	modelMap.put("errno", 0);
	        	modelMap.put("pathUrl", pathUrl);
		        modelMap.put("fileName", fileId);
	        }
//	        response.getWriter().write(json);
//	        response.getWriter().flush();
//	        response.getWriter().close();
	        
	        
	    }catch (Exception e) {
	        e.printStackTrace();
	        modelMap.put("errno", 1);
	        modelMap.put("errMsg", "上传图片失败");
	    }
	    return modelMap;
		
	}
	
	
	/**
	 * 删除发布商品
	 */
//	@RequestMapping(value="/removePublish",method=RequestMethod.GET)
//	@ResponseBody
	public Map<String,Object>removePublish(@RequestParam("source_id") String sourceId){
		Map<String,Object>modelMap=new HashMap<>();
		if(sourceId==null||sourceId=="") {
			modelMap.put("ernno", 1);//订单id为空
			return modelMap;
		}
		publishService.removePublish(Integer.parseInt(sourceId));
		modelMap.put("ernno", 0);//删除成功
		return modelMap;
	}
	
	/**
	 * 修改发布商品
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(value="/alterPublish",method=RequestMethod.GET)
	@ResponseBody
	public Map<String,Object>alterPublish(@RequestParam("source_id") String sourceId,
			@RequestParam("source_name")String source_name,@RequestParam("source_price")String sourceprice,
			@RequestParam("source_deposit")String sourcedeposit,@RequestParam("source_text")String source_text,
			@RequestParam("source_count")String sourcecount) throws UnsupportedEncodingException{
		
		Map<String,Object>modelMap=new HashMap<>();
		if(sourceId==null || sourceId=="undefined" || source_name==null || sourceprice==null
			||sourcedeposit==null || source_text==null || sourcecount==null) {
			modelMap.put("ernno", 1);//传值为空
			return modelMap;
		}
		
		SourceDetail sourceDetail = new SourceDetail();
		sourceDetail.setSourceId(Integer.parseInt(sourceId));
		source_name=new String(source_name.getBytes("ISO8859-1"),"UTF-8");
		source_text=new String(source_text.getBytes("ISO8859-1"),"UTF-8");
		sourceDetail.setSource_name(source_name);
		sourceDetail.setSource_deposit(Double.parseDouble(sourcedeposit));
		sourceDetail.setSource_price(Double.parseDouble(sourceprice));
		sourceDetail.setSource_text(source_text);
		sourceDetail.setSource_count(Integer.parseInt(sourcecount));
		System.out.println("sourceDetail: "+sourceDetail);
		publishService.updatePublish(sourceDetail);
		
		SourceDetail alterSourceDetail=sourceDetailService.findSourceById(Integer.parseInt(sourceId));
		if(alterSourceDetail!=null) {
			modelMap.put("ernno", 0);//修改成功
			modelMap.put("alterSourceDetail", alterSourceDetail);
		}
		return modelMap;
	}
	
}
